package com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.repository.HddcB1GeomorplyhasgeosvyptNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.repository.HddcB1GeomorplyhasgeosvyptRepository;
import com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.repository.entity.HddcB1GeomorplyhasgeosvyptEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.service.HddcB1GeomorplyhasgeosvyptService;
import com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.viewobjects.HddcB1GeomorplyhasgeosvyptPageVO;
import com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.viewobjects.HddcB1GeomorplyhasgeosvyptQueryParams;
import com.css.zfzx.sjcj.modules.hddcB1GeomorPlyHasGeoSvyPt.viewobjects.HddcB1GeomorplyhasgeosvyptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB1GeomorplyhasgeosvyptServiceImpl implements HddcB1GeomorplyhasgeosvyptService {

    private final HddcB1GeomorplyhasgeosvyptRepository hddcB1GeomorplyhasgeosvyptRepository;
    private final HddcB1GeomorplyhasgeosvyptNativeRepository hddcB1GeomorplyhasgeosvyptNativeRepository;
    private final SurfaceGeomorphicPointExcelVerifyHandler surfaceGeomorphicPointExcelVerifyHandler;

    @Autowired
    public HddcB1GeomorplyhasgeosvyptServiceImpl(HddcB1GeomorplyhasgeosvyptRepository hddcB1GeomorplyhasgeosvyptRepository,
                                                 HddcB1GeomorplyhasgeosvyptNativeRepository hddcB1GeomorplyhasgeosvyptNativeRepository,
                                                 SurfaceGeomorphicPointExcelVerifyHandler surfaceGeomorphicPointExcelVerifyHandler) {
        this.hddcB1GeomorplyhasgeosvyptRepository = hddcB1GeomorplyhasgeosvyptRepository;
        this.hddcB1GeomorplyhasgeosvyptNativeRepository = hddcB1GeomorplyhasgeosvyptNativeRepository;
        this.surfaceGeomorphicPointExcelVerifyHandler = surfaceGeomorphicPointExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB1Geomorplyhasgeosvypts(HddcB1GeomorplyhasgeosvyptQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcB1GeomorplyhasgeosvyptPageVO> hddcB1GeomorplyhasgeosvyptPage = this.hddcB1GeomorplyhasgeosvyptNativeRepository.queryHddcB1Geomorplyhasgeosvypts(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB1GeomorplyhasgeosvyptPage);
    }

    @Override
    public HddcB1GeomorplyhasgeosvyptEntity getHddcB1Geomorplyhasgeosvypt(String id) {
        return this.hddcB1GeomorplyhasgeosvyptRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1GeomorplyhasgeosvyptEntity saveHddcB1Geomorplyhasgeosvypt(HddcB1GeomorplyhasgeosvyptEntity hddcB1Geomorplyhasgeosvypt) {
        String uuid = UUIDGenerator.getUUID();
        hddcB1Geomorplyhasgeosvypt.setUuid(uuid);
        hddcB1Geomorplyhasgeosvypt.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB1Geomorplyhasgeosvypt.setCreateTime(now);
        hddcB1Geomorplyhasgeosvypt.setUpdateTime(now);
        hddcB1Geomorplyhasgeosvypt.setIsValid(PlatformConstants.Y);
        hddcB1Geomorplyhasgeosvypt.setQualityinspectionStatus(PlatformConstants.N);
        hddcB1Geomorplyhasgeosvypt.setExtends10(PlatformConstants.Y);
        this.hddcB1GeomorplyhasgeosvyptRepository.save(hddcB1Geomorplyhasgeosvypt);
        return hddcB1Geomorplyhasgeosvypt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB1GeomorplyhasgeosvyptEntity updateHddcB1Geomorplyhasgeosvypt(HddcB1GeomorplyhasgeosvyptEntity hddcB1Geomorplyhasgeosvypt) {
        HddcB1GeomorplyhasgeosvyptEntity entity = hddcB1GeomorplyhasgeosvyptRepository.findById(hddcB1Geomorplyhasgeosvypt.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcB1Geomorplyhasgeosvypt);
        hddcB1Geomorplyhasgeosvypt.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB1Geomorplyhasgeosvypt.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB1GeomorplyhasgeosvyptRepository.save(hddcB1Geomorplyhasgeosvypt);
        return hddcB1Geomorplyhasgeosvypt;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB1Geomorplyhasgeosvypts(List<String> ids) {
        List<HddcB1GeomorplyhasgeosvyptEntity> hddcB1GeomorplyhasgeosvyptList = this.hddcB1GeomorplyhasgeosvyptRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcB1GeomorplyhasgeosvyptList) && hddcB1GeomorplyhasgeosvyptList.size() > 0) {
            for (HddcB1GeomorplyhasgeosvyptEntity hddcB1Geomorplyhasgeosvypt : hddcB1GeomorplyhasgeosvyptList) {
//                this.hddcB1GeomorplyhasgeosvyptRepository.delete(hddcB1Geomorplyhasgeosvypt);
                hddcB1Geomorplyhasgeosvypt.setIsValid(PlatformConstants.N);
                hddcB1Geomorplyhasgeosvypt.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB1Geomorplyhasgeosvypt.setUpdateTime(new Date());
                this.hddcB1GeomorplyhasgeosvyptRepository.save(hddcB1Geomorplyhasgeosvypt);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB1GeomorplyhasgeosvyptQueryParams queryParams, HttpServletResponse response) {
        List<HddcB1GeomorplyhasgeosvyptEntity> yhDisasterEntities = hddcB1GeomorplyhasgeosvyptNativeRepository.exportYhDisasters(queryParams);
        List<HddcB1GeomorplyhasgeosvyptVO> list = new ArrayList<>();
        for (HddcB1GeomorplyhasgeosvyptEntity entity : yhDisasterEntities) {
            HddcB1GeomorplyhasgeosvyptVO yhDisasterVO = new HddcB1GeomorplyhasgeosvyptVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地貌面与地质地貌点关联表", "地貌面与地质地貌点关联表",
                HddcB1GeomorplyhasgeosvyptVO.class, "地貌面与地质地貌点关联表.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(surfaceGeomorphicPointExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB1GeomorplyhasgeosvyptVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB1GeomorplyhasgeosvyptVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB1GeomorplyhasgeosvyptVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB1GeomorplyhasgeosvyptVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @return
     */
    public void saveDisasterList(List<HddcB1GeomorplyhasgeosvyptVO> list) {
        for (int i = 0; i < list.size(); i++) {
            HddcB1GeomorplyhasgeosvyptEntity yhDisasterEntity = new HddcB1GeomorplyhasgeosvyptEntity();
            HddcB1GeomorplyhasgeosvyptVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB1Geomorplyhasgeosvypt(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     *
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB1GeomorplyhasgeosvyptEntity> hddcDataList = this.hddcB1GeomorplyhasgeosvyptRepository.queryByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB1GeomorplyhasgeosvyptEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid("0");
                this.hddcB1GeomorplyhasgeosvyptRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     *
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB1GeomorplyhasgeosvyptEntity> hddcDataList = this.hddcB1GeomorplyhasgeosvyptRepository.queryByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for (HddcB1GeomorplyhasgeosvyptEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid("0");
                this.hddcB1GeomorplyhasgeosvyptRepository.save(entity);
            }
        }
    }
}
